import { useRequest } from "ahooks";
import { useEffect, useRef, useState } from "react"


export default ({
    api,//请求接口
    manual=false,//是否不自动请求
    extraParams={},
    fieldParams={ //分页参数字段映射
        pageSize:'pageSize',
        pageCurrent:'pageCurrent',
        totalCount:'totalCount',
    },
}) =>{
    const [list,setList] = useState([]);
    const pageParams = useRef({
        [fieldParams.pageSize]:10,
        [fieldParams.pageCurrent]:1,
        [fieldParams.totalCount]:0,
    });
    const nextPage = () =>{
        pageParams.current[fieldParams.pageCurrent] += 1;
        run()
    }
    const {run,loading} = useRequest(()=>api({[fieldParams.pageSize]:pageParams.current[fieldParams.pageSize],[fieldParams.pageCurrent]:pageParams.current[fieldParams.pageCurrent],...extraParams}),{
        manual:true,
        debounceWait:100,
        debounceMaxWait:10000,
        onSuccess:(res)=>{
            setList(list.concat(res.list))
            pageParams.current[fieldParams.totalCount] = res[fieldParams.totalCount]
        }
    })
    useEffect(()=>{
        if(!manual){
            run();
        }
    },[manual])

    const refreshPage = () =>{
        pageParams.current[fieldParams.pageCurrent] = 1;
        pageParams.current[fieldParams.totalCount] = 0;
        setList([])
        run();
    }
    return {
        pageParams:pageParams.current,
        nextPage,
        list,
        refreshPage,
        loading,
    }
}